-- Leviathan (c) v.v.balashoff
local Class = require('leviathan/Class')
local Log = require('leviathan/Log')

local DomainSwitcherSystem = Class:derive('UIDomainSwitcherSystem')

function DomainSwitcherSystem:new(domain)
    self.name = 'DomainSwitcherSystem'
    self.domain = domain
end

function DomainSwitcherSystem:update(dt)
    local comps = self.domain.components['Core']
    if not comps then
        return
    end
    for i = 1, #comps do
        local comp = comps[i]
        if comp.id == 'DomainSwitcherComponent' then
            if comp.entity.enabled and comp.enabled then
                local fName = comp.domainFrom.name
                local toName = comp.domainTo
                Log:debug('[DomainSwitcherSystem] Switching domains: «'..fName..'» => «'..toName..'»')
                comp.entity.enabled = false
                if comp.keep then
                    Log:warning('[DomainSwitcherSystem] Keeping domain:'..fName)
                end
                world:switchDomain(comp.domainFrom, comp.domainTo, comp.keep)
            end
        end
    end
end

return DomainSwitcherSystem
